import { ref, Ref } from 'vue'
import dayjs from 'dayjs'

/**
 * 创建一个响应式的当前时间对象
 */
export function useCurrentTime() {
  const currentTime: Ref<dayjs.Dayjs> = ref(dayjs())
  const nextIteration = ref(true)
  let timerId: ReturnType<typeof setTimeout> | null
  start()

  function updateTime() {
    if (nextIteration.value) {
      // console.log('定时器更新中');
      currentTime.value = dayjs()
      timerId = setTimeout(updateTime, 1000)
    }
  }

  function start() {
    nextIteration.value = true
    updateTime()
  }

  function stop() {
    nextIteration.value = false
    timerId && clearTimeout(timerId)
  }

  return { currentTime, start, stop }
}

// 避免重复定义创造大量定时器
const { currentTime, start, stop } = useCurrentTime()
export { currentTime, start, stop }
